package org.im.service.websocket.server;

import java.io.IOException;
import java.util.Collection;

import javax.websocket.Session;

import org.im.service.message.bean.rs.ErrMessageType;
import org.im.service.message.exp.MessageException;
import org.im.service.message.util.MessageUtil;
import org.im.service.message.webmsg.WebMessage;
import org.im.service.websocket.server.pool.WebsocketSessionPool;

public class WebsocketMessageContext {

    public static void createWebsocketPipeline(Session session) {
        System.out.println("创建新的通信通道: " + session.getId());
        WebsocketSessionPool.addSession(session);
    }

    public static void distroyWebsocketPipeline(Session session) {
        System.out.println("销毁通信通道: " + session.getId());
        WebsocketSessionPool.removeSession(session);
    }

    public static void sendMessage(Session from, String toId, String message) throws MessageException {
        Session to = WebsocketSessionPool.getSession(toId);
        if (to == null) {
            throw ErrMessageType.NONE_RECEIVER_ERRO.toMessageResult();
        }

        try {
            to.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendMessageToSession(Session from, String message) throws MessageException {
        WebMessage webMessage = MessageUtil.createMessageFromString(message);

        if (webMessage == null) {
            throw ErrMessageType.DECODE_ERROR.toMessageResult();
        }

        if (!webMessage.getSenderId().equalsIgnoreCase(from.getId())) {
            throw ErrMessageType.ILLEGAL_OP.toMessageResult();
        }
        sendMessage(from, webMessage.getRecipientId(), message);
        sendMessage(from, from.getId(), message);
    }

    public static void sendMessageToSession(Session from, Collection<String> sessionIds, String message) throws MessageException {
        WebMessage webMessage = MessageUtil.createMessageFromString(message);

        if (webMessage == null) {
            throw ErrMessageType.DECODE_ERROR.toMessageResult();
        }

        if (sessionIds != null && sessionIds.size() > 0) {
            for (String to : sessionIds) {
                try {
                    sendMessage(from, to, message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
